package main

import (
	"context"
	"fmt"
	"github.com/apache/pulsar-client-go/pulsar"
	"log"
	"pulsar-go/utils"
)

var client pulsar.Client
var producer pulsar.Producer
var err error
var done = make(chan bool)

func main() {
	send()
	utils.Reserve()
}

func send() {
	// 创建Pulsar客户端
	if client, err = utils.BuildClint(); err != nil {
		log.Printf("获取连接失败:%s\n", err.Error())
		return
	}
	defer client.Close()

	// 创建消费者
	if producer, err = utils.BuildProducer(client); err != nil {
		log.Printf("消息发送端获取连接失败:%v\n", err.Error())
		return
	}
	defer producer.Close()

	log.Println("连接成功,请在下方输出并回车发送消息")
	ctx := context.Background()

	go func() {
		for true {
			var message string
			var e error
			if _, e = fmt.Scanln(&message); e != nil {
				log.Println("获取数据失败,原因是:", e.Error())
				if message == "" {
					log.Println("接收到空消息")
					continue
				} else {
					done <- true
					break
				}
			}

			if message == "exit" {
				log.Println("停止发送")
				done <- true
				break
			}
			send, err := producer.Send(ctx, &pulsar.ProducerMessage{
				Payload: []byte(message),
			})
			if err != nil {
				log.Println("发送失败,原因是:", err.Error())
				done <- true
				break
			}
			log.Println("发送成功", send.EntryID())
		}
	}()
	<-done // 等待协程的完成信号
}
